﻿Imports System.IO
Imports System.Xml

Public Class clsLogger
    Dim Counter As Integer = 0
    Dim PointCounter As Integer = 0
    Dim PointReset As Integer = 0
    
    Public Sub New()
        Try
            Dim F As String = String.Format("{0}-{1}{2}{3}{4}{5}{6}.kml", Glob.MobileSettings.FileTag, Now.Day, Now.Month, Now.Year, Now.Hour, Now.Minute, Now.Second)
            Me.FileName = Path.Combine(Glob.MobileSettings.KMLFolder, F)
            Dim XMLTemplateFile = Path.Combine(Glob.MobileSettings.AppPath, "template.xml")
            Me.XMLDoc = New Xml.XmlDocument
            Me.XMLDoc.Load(XMLTemplateFile)
            Me.KMLSettings()
        Catch ex As Exception
            PushLog("Error in clsLogger.New: " & ex.Message)
        End Try
    End Sub

    Public Sub KMLSettings()
        Try
            Dim F As String = String.Format("{0}-{1}{2}{3}{4}{5}{6}.kml", Glob.MobileSettings.FileTag, Now.Day, Now.Month, Now.Year, Now.Hour, Now.Minute, Now.Second)
            Me.FileName = Path.Combine(Glob.MobileSettings.KMLFolder, F)
            Me.SetNodeText("//kml/Document/Style/LineStyle/color", modUtil.ColorName2RGB(Glob.MobileSettings.LineColor))
            Me.SetNodeText("//kml/Document/Style/LineStyle/width", Glob.MobileSettings.LineWidth.ToString)
        Catch ex As Exception
            PushLog("Error in clsLogger.KMLSettings: " & ex.Message)
        End Try
    End Sub

    Private _FileName As String
    Public Property FileName() As String
        Get
            Return _FileName
        End Get
        Set(ByVal value As String)
            _FileName = value
        End Set
    End Property

    Private _XMLDoc As System.Xml.XmlDocument
    Private Property XMLDoc() As System.Xml.XmlDocument
        Get
            Return _XMLDoc
        End Get
        Set(ByVal value As System.Xml.XmlDocument)
            _XMLDoc = value
        End Set
    End Property


    Private _Position As Microsoft.WindowsMobile.Samples.Location.GpsPosition
    <CLSCompliant(False)> _
    Public Property Position() As Microsoft.WindowsMobile.Samples.Location.GpsPosition
        Get
            Return _Position
        End Get
        Set(ByVal value As Microsoft.WindowsMobile.Samples.Location.GpsPosition)
            Try
                _Position = value
                If value.LatitudeValid Then
                    UpdateXML()
                    PointReset += 1
                    If PointReset > Glob.MobileSettings.RecordPositionEvery Then
                        Me.LogPoint()
                        PointReset = 0
                    End If
                End If
            Catch ex As Exception
                PushLog("Error in clsLogger.Position.Set: " & ex.Message)
            End Try
        End Set
    End Property

    Private Sub UpdateXML()
        Try
            Dim Pat As String = "{0},{1},{2} "
            Dim Pos As String = String.Format(Pat, Me.Position.Longitude, Me.Position.Latitude, Me.Position.EllipsoidAltitude)
            Me.SetNodeText("//kml/Document/Placemark/LineString/coordinates", Pos, True)
            'Counter += 1
            'If Counter = 100 Then
            Me.Save()
            Me.Counter = 0
            'End If
        Catch ex As Exception
            PushLog("Error in clsLogger.UpdateXML: " & ex.Message)
        End Try
    End Sub

    Private Sub SetNodeText(ByVal xPath As String, ByVal Value As String, Optional ByVal Append As Boolean = False)
        Try
            Dim objNode As Xml.XmlNode
            objNode = XMLDoc.DocumentElement.SelectSingleNode(xPath)
            If Append Then
                objNode.InnerText &= Value
            Else
                objNode.InnerText = Value
            End If
        Catch ex As Exception
            PushLog("Error in clsLogger.SetNodeText: " & ex.Message)
        End Try
    End Sub

    ''' <summary>
    ''' Save the KML file for Google Map
    ''' </summary>
    ''' <remarks></remarks>
    Public Sub Save()
        Try
            Dim MS As New System.IO.MemoryStream
            XMLDoc.Save(MS)
            MS.Flush()
            MS.Position = 0
            Dim StReader As New StreamReader(MS)
            Dim FileContent As String = StReader.ReadToEnd
            FileContent = FileContent.Replace("<kml>", "<?xml version=""1.0"" encoding=""UTF-8""?>" & vbNewLine & "<kml xmlns=""http://www.opengis.net/kml/2.2"" xmlns:gx=""http://www.google.com/kml/ext/2.2"" xmlns:kml=""http://www.opengis.net/kml/2.2"" xmlns:atom=""http://www.w3.org/2005/Atom"">")
            Dim StWriter As New System.IO.StreamWriter(Me.FileName)
            StWriter.Write(FileContent)
            StWriter.Flush()
            StWriter.Close()
        Catch ex As Exception
            PushLog("Error in clsLogger.Save: " & ex.Message)
        End Try
    End Sub

    ''' <summary>
    ''' Push a point into the KML (XML) file
    ''' </summary>
    ''' <remarks></remarks>
    Public Sub LogPoint()
        Try
            PointCounter += 1
            Dim KMLPoint = <Placemark>
                               <name>My Mark2</name>
                               <description></description>
                               <LookAt>
                                   <longitude></longitude>
                                   <latitude></latitude>
                                   <altitude></altitude>
                                   <range>400</range>
                                   <tilt>0</tilt>
                                   <heading>0</heading>
                                   <altitudeMode>relativeToGround</altitudeMode>
                               </LookAt>
                               <Point>
                                   <coordinates></coordinates>
                               </Point>
                           </Placemark>

            KMLPoint.<name>.Value = String.Format("Point #{0}", PointCounter)
            KMLPoint.<description>.Value = Me.PointDescBuilder
            KMLPoint.<LookAt>.<longitude>.Value = Me.Position.Longitude
            KMLPoint.<LookAt>.<latitude>.Value = Me.Position.Latitude
            KMLPoint.<LookAt>.<altitude>.Value = Me.Position.EllipsoidAltitude
            KMLPoint.<Point>.<coordinates>.Value = String.Format("{0},{1},{2}", Me.Position.Longitude, Me.Position.Latitude, Me.Position.EllipsoidAltitude)
            Me.XMLDoc.FirstChild.FirstChild.InnerXml &= KMLPoint.ToString
        Catch ex As Exception
            PushLog("Error in clsLogger.LogPoint: " & ex.Message)
        End Try
    End Sub

    ''' <summary>
    ''' Location description template
    ''' </summary>
    ''' <returns>Formated KML point location</returns>
    ''' <remarks></remarks>
    Private Function PointDescBuilder() As String
        Try
            Dim objPosition As New clsPosition(Me.Position)
            Dim StrBuild As New System.Text.StringBuilder
            StrBuild.Append("Date: ")
            StrBuild.Append(Now.ToShortDateString)
            StrBuild.Append(" ")
            StrBuild.AppendLine(Now.ToShortTimeString)
            StrBuild.Append("Speed: ")
            StrBuild.AppendLine(objPosition.Speed.ToString("F2") & " km/h")
            StrBuild.Append("Distance: ")
            StrBuild.AppendLine(Glob.DistanceCalc.Distance.ToString("F2") & " km")
            StrBuild.Append("Fuel Cons: ")
            StrBuild.AppendLine(Glob.FuelConsumption.Litres.ToString("F2") & " L")
            StrBuild.Append("Fuel Cost: ")
            StrBuild.AppendLine(Glob.FuelConsumption.Cost.ToString("F2") & " LL")
            StrBuild.Append("Accuracy: ")
            StrBuild.AppendLine(objPosition.PositionAccuracy.ToString("F2") & "%")
            StrBuild.Append("Sat #: ")
            StrBuild.Append(objPosition.SatCount)
            Return StrBuild.ToString
        Catch ex As Exception
            PushLog("Error in clsLogger.PointDescBuilder: " & ex.Message)
            Return String.Empty
        End Try
    End Function

End Class
